import http from 'wechat-http'

// 仿照了axios
http.baseURL = 'https://live-api.itheima.net'

// 相应拦截器
http.intercept.response = async ({ statusCode, data, config }) => {

  const app = getApp()

  if(statusCode === 401) {

    if(config.url.includes('/refreshToken')) {
      return wx.redirectTo({
        url: '/pages/login/index'
      })
    }
    if(!app.refresh_token) return
    const res = await http({
      url: '/refreshToken',
      method: 'POST',
      header: {
        Authorization: app.refresh_token,
      }
    })
    // 更新token
    app.setToken(res.data.token, res.data.refreshToken)

    return http(
      Object.assign(config, {
        header: {
          Authorization: app.token,
        }
      })
    )

  }

  return data
}

http.intercept.request = (params) => {
  const { token } = getApp()
  const defaultHeader = {}

  if (token) defaultHeader.Authorization = token

  params.header = Object.assign(defaultHeader, params.header)

  return params
}

// 挂载到全局对象 wx 中
wx.http = http

export default http